package com.tanhua.server.server;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domian.Announcement;
import com.tanhua.model.domian.User;
import com.tanhua.model.domian.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MessageService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private FriendApi friendApi;
    @DubboReference
    private CommentsApi commentsApi;
    @DubboReference
    private AnnouncementApi announcementApi;

    /**
     * 根据环信ID查询用户详细信息
     * @param huanxinId
     * @return
     */
    public UserInfoVo findHuanXinUserInfo(String huanxinId) {
        //根据user表 找到user数据
        User user = userApi.findHuanxinId(huanxinId);
        //从user数据里面取出id，根据ID找到 userinfo表里面的信息
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //封装VO对象
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        if (userInfo.getAge()!=null){
             userInfoVo.setAge(userInfoVo.getAge());
        }
        return userInfoVo;
    }

    public void addFriend(Long friendId) {
        //将好友关系注册到环信
        Long userId = UserHolder.getUserId();
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + friendId);
        if (!aBoolean){
            //添加失败，抛出异常
            throw new BusinessException(ErrorResult.error());
        }
        //添加成功，friend的表中加入数据
       friendApi.addFriend(userId,friendId);
    }

    public PageResult friendList(Integer page, Integer pagesize, String keyword) {
        Long userId = UserHolder.getUserId();
        //查询当前用户的好友数据
        List<Friend> list = friendApi.findByUserId(userId,page,pagesize);
        //判断是否为空
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //提取friend表中的好友数据
        List<Long> friendIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //调用userinfo表查询好友详细
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds, userInfo);
        //构建VO对象
        ArrayList<ContactVo> vo = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo1 = map.get(friend.getFriendId());
            if (userInfo1 != null) {
                ContactVo init = ContactVo.init(userInfo1);
                vo.add(init);
            }
        }
        return new PageResult(page,pagesize,01,vo);
    }

    /**
     * 点赞列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult lists(Integer page, Integer pagesize ,int CommentType) {
         //获取账户ID
        Long userId = UserHolder.getUserId();
        //依靠账户ID查询到comment表，取出被点赞的数据 的时间封装到likeListvo
        List<Comment> list = commentsApi.findPublisUserId(userId,page,pagesize, CommentType);
        //判断有无有无取出来的点赞数
        if (list == null){
            throw new BusinessException(ErrorResult.error());
        }
        //依靠被点赞的数据，找到被谁点赞的Userinfo信息封装到likeListvo
        List<Long> userIds = CollUtil.getFieldValues(list, "publishUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        ArrayList<LikeListVo> likeListVos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getPublishUserId());
            if (userInfo != null){
                LikeListVo likeListVo = new LikeListVo();
                likeListVo.setId(userInfo.getId().toString());
                likeListVo.setNickname(userInfo.getNickname());
                likeListVo.setAvatar(userInfo.getAvatar());
                Long created = comment.getCreated();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(created);
                String dateString = formatter.format(date);
                likeListVo.setCreateDate(dateString);
                likeListVos.add(likeListVo);
            }
        }
       return new PageResult(page,pagesize,01,likeListVos);
    }

    /**
     * 获取喜欢列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult loves(Integer page, Integer pagesize) {
        //获取账户ID
        Long userId = UserHolder.getUserId();
        //依靠账户ID查询到comment表，取出被点赞的数据 的时间封装到likeListvo
        List<Comment> list = commentsApi.findPublisUserId(userId,page,pagesize, CommentType.LOVE.getType());
        //判断有无有无取出来的点赞数
        if (list == null){
            throw new BusinessException(ErrorResult.error());
        }
        //依靠被点赞的数据，找到被谁点赞的Userinfo信息封装到likeListvo
        List<Long> userIds = CollUtil.getFieldValues(list, "publishUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        ArrayList<LikeListVo> likeListVos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getPublishUserId());
            if (userInfo != null){
                LikeListVo likeListVo = new LikeListVo();
                likeListVo.setId(userInfo.getId().toString());
                likeListVo.setNickname(userInfo.getNickname());
                likeListVo.setAvatar(userInfo.getAvatar());
                Long created = comment.getCreated();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(created);
                String dateString = formatter.format(date);
                likeListVo.setCreateDate(dateString);
                likeListVos.add(likeListVo);
            }
        }
        return new PageResult(page,pagesize,01,likeListVos);
    }

    public PageResult announcements(Integer page, Integer pagesize) {
       List<Announcement> list =  announcementApi.announcements(page,pagesize);
       List<AnnouncementVo> vo = new ArrayList<>();
        for (Announcement announcement : list) {
            if (announcement!=null){
                AnnouncementVo announcementVo = new AnnouncementVo();
                announcementVo.setCreateDate(announcement.getDescription());
                announcementVo.setId(announcement.getId());
                announcementVo.setTitle(announcement.getTitle());
                announcementVo.setDescription(announcement.getDescription());
                vo.add(announcementVo);
            }
        }
        return new PageResult(page,pagesize,01,vo);
    }
}
